package com.desire.homework;

import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author desire
 */
public class _48_斐波那契数列 {
    public static void main1(String[] args) {
        IntStream is = IntStream.range(0, 2);
        is.forEach(System.out::print); // 0 1

        System.out.println();

        // seed 开始值
        IntStream is2 = IntStream.iterate(5, (e) -> e + 1).limit(5);
        is2.forEach(System.out::print); // 0 1 2 3 4

        System.out.println();

        IntStream is3 = IntStream.iterate(0, e -> true, e -> e + 1).limit(3);
        is3.forEach(System.out::print);

        System.out.println();

        //java Stream Fibonacci series
        var s = Stream.iterate(List.of(0, 1), i -> List.of(i.get(1), i.get(0) + i.get(1))).limit(15);
        s.forEach(e -> {
            System.out.printf("%d ", e.get(1));
        });
    }

    /**
     * 斐波那契数列算法，从第三个数开始，每个数是前两个数之和：1 1 2 3 5 8 13 21 34 55
     * 求第N个数的两种算法，分递归和非递归两种
     */
    public static void main(String[] args) {
        System.out.println(f(20));
        System.out.println(fx(20));
    }

    //递归方式
    public static int f(int n) {
        //参数合法性验证
        if (n < 1) {
            System.out.println("参数必须大于1！");
            System.exit(-1);
        }
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }

    //非递归方式
    public static int fx(int n) {
        //参数合法性验证
        if (n < 1) {
            System.out.println("参数必须大于1！");
            System.exit(-1);
        }
        //n为1或2时候直接返回值
        if (n == 1 || n == 2) {
            return 1;
        }

        //n>2时候循环求值
        int res = 0;
        int a = 1;
        int b = 1;
        for (int i = 3; i <= n; i++) {
            res = a + b;
            a = b;
            b = res;
        }
        return res;
    }
}

